﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Microsoft.AspNetCore.Mvc;
using WqLunTan.ConstConfig;
using WqLunTan.Filters;
using WqLunTan.Models.DataBase;

namespace WqLunTan.Areas.Manage.Controllers
{
    /// <summary>
    /// 网站相关设置控制器
    /// </summary>
    [Auth(AuthType = WqUserAuth.Manage)]
    public class SettingController : BaseManageController
    {
        /// <summary>
        /// 设置网站标题内容
        /// </summary>
        /// <returns></returns>
        public IActionResult SiteTitleName()
        {
            var titleConfig = DbContext.SiteConfig.Where(x => x.config_key.Equals(ConfigKey.SiteTitle)).SingleOrDefault() ?? new site_config();
            var user = DbContext.Users.Where(x => x.Id == titleConfig.uid).SingleOrDefault() ?? new WqUser();
            ViewData["titleConfig"] = titleConfig;
            ViewData["user"] = user;

            return View();
        }

        /// <summary>
        /// 更新网站的标题
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public IActionResult UpdateSiteTitle(site_config config)
        {
            if (!string.IsNullOrWhiteSpace(config.config_value))
            {
                var model = DbContext.SiteConfig.Where(x => x.config_key.Equals(ConfigKey.SiteTitle)).SingleOrDefault();
                if (model != null)
                {
                    model.config_value = config.config_value;
                    model.config_category = config.config_category ?? string.Empty;
                    model.description = config.description ?? string.Empty;
                    model.last_update = DateTimeOffset.UtcNow;
                }
                else
                {
                    config.uid = LoginUser.Id;
                    config.create_time = DateTimeOffset.UtcNow;
                    config.last_update = DateTimeOffset.UtcNow;
                    config.config_key = ConfigKey.SiteTitle;
                    config.config_category = config.config_category ?? string.Empty;
                    config.description = config.description ?? string.Empty;
                    DbContext.SiteConfig.Add(config);
                }
                httpCacheHelper.setCache(ConfigKey.SiteTitle, config, 10);
                DbContext.SaveChanges();
            }
            return JsonOkResult("保存成功");
        }
    }
}